package com.atguigu.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class MySelfDemo{
    Lock lock=new ReentrantLock();

    public synchronized void  m1(){
        System.out.println(Thread.currentThread().getName()+"----------");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void m2() throws InterruptedException {
           if (lock.tryLock(2,TimeUnit.SECONDS)){
               try {
                   System.out.println(Thread.currentThread().getName()+"----------");
                   try {
                       TimeUnit.SECONDS.sleep(2);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               } finally {
                   lock.unlock();
               }
           }else {
               System.out.println("手速太慢了！！！！抢锁失败！！！");
           }



    }
}
//线程调用资源类
public class SyncVsReentrantLockDemo {
    public static void main(String[] args) {
        MySelfDemo mySelfDemo = new MySelfDemo();
     /*   new Thread(() ->{ { mySelfDemo.m1();} },"线程1").start();

        new Thread(() ->{ { mySelfDemo.m1();} },"线程2").start();*/

        new Thread(() ->{ {
            try {
                mySelfDemo.m2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } },"线程1").start();

        new Thread(() ->{ {
            try {
                mySelfDemo.m2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } },"线程2").start();
    }
}
